package cn.cs.common;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Component
public class UploadUtil {
  static  String rootPath="/usr/local/image/";

    private static final Logger log = LoggerFactory.getLogger(UploadUtil.class);

    /**
     * 生成上传文件名
     *可以不用
     * @return
     */
    public static String creatName() {
        String time = Long.toString(System.currentTimeMillis());
        String rand = Integer.toString(((int) (Math.random() * 10000)));
        return time + rand;
    }

    /**
     * 图片处理上传
     *
     * @param fileUrl    图片地址
     * @param filesuffix 图片后缀名
     * @return 新文件名
     */
    public static String imageProcess(String fileUrl, String filesuffix) {
        //图片像素处理
        //生成新的文件名
        String newName = creatName() + "." + filesuffix;
        try {
            return newName;
        } catch (Exception e) {
            log.error("图片上传失败", e);
            return "error";
        }
    }


    /**
     * 删除临时文件
     *
     * @param dir        文件目录
     * @param fileName   文件名
     * @param filesuffix 文件后缀名
     */
    public static void deleteDir(File dir, String fileName, String filesuffix, String type) {
        if (dir.isDirectory()) {
            if ("img".equals(type)) {
                File file = new File(dir, fileName);
                file.delete();
            } else {
                File file = new File(dir, fileName);
                file.delete();
            }

        }
    }

    /**
     * 上传文件
     *
     * @param request
     * @param type
     * @return
     * @throws UnsupportedEncodingException
     */
    public static UploadInfo upload(HttpServletRequest request, String type, String secondary) throws UnsupportedEncodingException {
        /*
         * 加载imgurl
       *
       */
        String imgUrl = rootPath;
        long size = 0;
        String realFilePath = imgUrl + secondary; // 先上传到此目录下
        MultipartHttpServletRequest multipRequest = (MultipartHttpServletRequest) request;
        multipRequest.setCharacterEncoding("utf-8");
        Map<String, MultipartFile> fileMap = multipRequest.getFileMap();
        MultipartFile mfile = null;
        //当前域名
        String name = "";      //原文件名
        String oldName = "";   //原文件名没有后缀
        String newName = "";   //新文件名(没有后缀)
        String filesuffix = "";//文件后缀名
        // 没有获取到上传的文件信息
        if (fileMap.entrySet().size() == 0) {
            return null;
        }

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            mfile = entity.getValue();
            if (mfile != null && mfile.getSize() > 0) {
                name = mfile.getOriginalFilename();
                size = mfile.getSize();
                //获取文件后缀名
                filesuffix = name.substring(name.lastIndexOf(".") + 1);
                oldName = name.replace("." + filesuffix, "");
                //System.out.println(size + " " + type);
                if (name == null || name.trim().equals("")) {
                    continue;
                }
                //如果没有文件夹则创建
                if (!(new File(realFilePath).isDirectory())) {
                    new File(realFilePath).mkdirs();
                }
//                if ("img".equals(type)) {
//                    newName = imageProcess(realFilePath + "/" + name, filesuffix);
//                } else if ("accessory".equals(type)) {
//                    Date date = new Date();
//                    newName = oldName + date.getTime() + "." + filesuffix;
//                }
                  newName = realFilePath + "/"+name;
                File saveFile = new File(newName);
                //保存文件
                try {
                    mfile.transferTo(saveFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("文件保存出错！" + e.getMessage());
                    return null;
                }
            }
        }

        UploadInfo ui = new UploadInfo();
        ui.setOldName(name);
        ui.setPath(newName);//imgUpload.getNewName()
        ui.setNewName(newName);
        ui.setSize(size + "");
        return ui;
    }

    /**
     * 上传文件
     *
     * @param
     * @param
     * @return
     * @throws UnsupportedEncodingException
     */
    public static UploadInfo uploadFile(MultipartFile file, String secondary) throws UnsupportedEncodingException {
        /*
         * 加载imgurl
       *
       */
        String imgUrl = rootPath;
        long size = 0;
        String realFilePath = imgUrl + secondary; // 先上传到此目录下
        //当前域名
        String name = "";      //原文件名
        String oldName = "";   //原文件名没有后缀
        String newName = "";   //新文件名(没有后缀)
        String filesuffix = "";//文件后缀名
        // 没有获取到上传的文件信息
            if (file != null && file.getSize() > 0) {
                name = file.getOriginalFilename();
                size = file.getSize();
                //获取文件后缀名
                filesuffix = name.substring(name.lastIndexOf(".") + 1);
                oldName = name.replace("." + filesuffix, "");
                //System.out.println(size + " " + type);

                //如果没有文件夹则创建
                if (!(new File(realFilePath).isDirectory())) {
                    new File(realFilePath).mkdirs();
                }
//                if ("img".equals(type)) {
//                    newName = imageProcess(realFilePath + "/" + name, filesuffix);
//                } else if ("accessory".equals(type)) {
//                    Date date = new Date();
//                    newName = oldName + date.getTime() + "." + filesuffix;
//                }
                newName = realFilePath + "/"+name;
                File saveFile = new File(newName);
                //保存文件
                try {
                    file.transferTo(saveFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("文件保存出错！" + e.getMessage());
                    return null;
                }
            }
        UploadInfo ui = new UploadInfo();
        ui.setOldName(name);
        ui.setPath(newName);//imgUpload.getNewName()
        ui.setNewName(newName);
        ui.setSize(size + "");
        return ui;
    }

    /**
     * 图片上传
     *
     * @param request
     * @return
     */
    public static UploadInfo imgUpload(HttpServletRequest request, String secondary) {
        UploadInfo ui = null;
        try {
            ui = upload(request, "img", secondary);
        } catch (UnsupportedEncodingException e) {
            //e.printStackTrace();
        }
        return ui;
    }

    /**
     * 附件上传
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    public static UploadInfo accessoryUpload(HttpServletRequest request, String secondary) throws UnsupportedEncodingException {
        UploadInfo ui = null;

        ui = upload(request, "accessory", secondary);

        return ui;
    }


    /**
     * 附件上传
     *
     * @param request
     * @return
     */
    public static UploadInfo fileUpload(HttpServletRequest request, String secondary) {
        UploadInfo ui = null;
        try {
            ui = upload(request, "file", secondary);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return ui;
    }

    /**
     * 删除服务上的文件
     *
     * @param filePath 路径
     * @return
     * @author W
     */
    public static boolean deleteServerFile(String filePath) {
        boolean delete_flag = false;
        try {
            File file = new File(filePath);
            if (file.exists() && file.isFile() && file.delete())
                delete_flag = true;
            else
                delete_flag = false;
        } catch (Exception e) {
            e.printStackTrace();
            delete_flag = false;
        }
        return delete_flag;
    }
    /**
     * 下载服务器上的文件
     *
     * @param name 带后缀的文件名称
     * @return
     * @author
     */
    public static void download(String path,String name, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename="
                    + new String(name));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(
                    response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=gb2312");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 上传文件
     *
     * @param request
     * @param type
     * @return
     * @throws UnsupportedEncodingException
     */
    public static List<UploadInfo> uploadFiles(HttpServletRequest request, String type, String secondary) throws UnsupportedEncodingException {
        List<UploadInfo> list =new ArrayList<UploadInfo>();
        String imgUrl = rootPath;
//        String imgUrl = "classpath:/image/";
        long size = 0;
        String realFilePath = imgUrl + secondary; // 先上传到此目录下
        MultipartHttpServletRequest multipRequest = (MultipartHttpServletRequest) request;
        multipRequest.setCharacterEncoding("utf-8");
        Map<String, MultipartFile> fileMap = multipRequest.getFileMap();
        if (fileMap.entrySet().size() == 0) {
            return null;
        }
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mfile = null;
            //当前域名
            String name = "";      //原文件名
            String oldName = "";   //原文件名没有后缀
            String newName = "";   //新文件名(没有后缀)
            String filesuffix = "";//文件后缀名
            // 没有获取到上传的文件信息
            mfile = entity.getValue();
            if (mfile != null && mfile.getSize() > 0) {
                name = mfile.getOriginalFilename();
                size = mfile.getSize();
                //获取文件后缀名
                filesuffix = name.substring(name.lastIndexOf(".") + 1);
                if (name == null || name.trim().equals("")) {
                    continue;
                }
                //如果没有文件夹则创建
                if (!(new File(realFilePath).isDirectory())) {
                    new File(realFilePath).mkdirs();
                }
                newName = realFilePath + "/"+name;
                File saveFile = new File(newName);
                //保存文件
                try {
                    mfile.transferTo(saveFile);
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("文件保存出错！" + e.getMessage());
                    return null;
                }
            }
            UploadInfo ui = new UploadInfo();
            ui.setOldName(name);
            ui.setKey(entity.getKey());
            ui.setPath(newName);//imgUpload.getNewName()
            ui.setNewName(newName);
            ui.setSize(size + "");
            list.add(ui);
        }
        return list;
    }


    public static UploadInfo fileUpload(MultipartFile file, String secondary) throws Exception {
        List<UploadInfo> list =new ArrayList<UploadInfo>();
        String filePath = rootPath; // 上传后的路径
        long size = 0;
        String realFilePath = filePath + secondary; // 先上传到此目录下

        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String randomCode = "";
        for (int i = 0; i < 6; i++) {
            Random random = new Random();
            randomCode += random.nextInt(10);
        }
        fileName = DateUtil.format(new Date(), "yyyyMMdd") + randomCode + suffixName; // 新文件名
        //如果没有文件夹则创建
        if (!(new File(realFilePath).isDirectory())) {
            new File(realFilePath).mkdirs();
        }
        File dest = new File(realFilePath + "/" + fileName);
        file.transferTo(dest);


        UploadInfo ui = new UploadInfo();
        ui.setNewName(fileName);
        return ui;
    }



    public static List<UploadInfo> filesUpload(HttpServletRequest request, String secondary) throws Exception {
        List<UploadInfo> list =new ArrayList<UploadInfo>();
        String filePath = rootPath; // 上传后的路径
        long size = 0;
        String realFilePath = filePath + secondary; // 先上传到此目录下
        MultipartHttpServletRequest multipRequest = (MultipartHttpServletRequest) request;
        multipRequest.setCharacterEncoding("utf-8");
        Map<String, MultipartFile> fileMap = multipRequest.getFileMap();
        if (fileMap.entrySet().size() == 0) {
            return null;
        }

        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mfile = entity.getValue();
            String fileName = mfile.getOriginalFilename();  // 文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
            String randomCode = "";
            for (int i = 0; i < 6; i++) {
                Random random = new Random();
                randomCode += random.nextInt(10);
            }
            fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss_") + randomCode + suffixName; // 新文件名
            //如果没有文件夹则创建
            if (!(new File(realFilePath).isDirectory())) {
                new File(realFilePath).mkdirs();
            }
            File dest = new File(realFilePath + "/" + fileName);
            mfile.transferTo(dest);


            UploadInfo ui = new UploadInfo();
            ui.setNewName(fileName);
            list.add(ui);
        }
        return list;
    }


 }
